﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using BCEntity.OA.TeamWork.TeamWorkReply;
using BCCommon;

namespace BCData.OA.TeamWork.TeamWorkReply
{
    /// <summary>
    /// 协同办公回复
    /// </summary>
    public class TeamWorkReplyData : ITeamWorkReplyData
    {
        private const string QUERY_EXISTS = @"SELECT 1 FROM OA_TeamWorkReply";
        private const string QUERY = @"SELECT A.TeamWorkReplyId,A.TeamWorkId,A.ParticipantId,A.ReplyType,A.TeamWorkAttachmentId,A.ReplyContent,A.ReplyTime,
                                            B.FileAddress,B.FileSource,C.ParticipantName,C.CompanyName,C.DepartmentName,C.JobTitle
                                        FROM OA_TeamWorkReply A
                                        LEFT JOIN OA_TeamWorkAttachment B ON A.TeamWorkAttachmentId=B.TeamWorkAttachmentId
                                        LEFT JOIN OA_TeamWorkParticipant C ON A.ParticipantId=C.ParticipantId AND A.TeamWorkId=C.TeamWorkId";
        
        private readonly IDatabaseContext databaseContext;

        public TeamWorkReplyData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public async Task<bool> Exists(long teamWorkReplyId)
        {
            string sql = string.Format(@"{0} WHERE TeamWorkReplyId=?TeamWorkReplyId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TeamWorkReplyId", teamWorkReplyId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<TeamWorkReplyEntity> Add(TeamWorkReplyEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_TeamWorkReply", new string[] { "TeamWorkId", "ParticipantId", "ReplyType", "ReplyTime", "ReplyContent", "TeamWorkAttachmentId" });
            sql = string.Format("{0} {1} WHERE A.TeamWorkReplyId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TeamWorkId", entity.TeamWorkId, DbType.Int64, size: 20);
            parameters.Add("?ParticipantId", entity.ParticipantId, DbType.Int64, size: 20);
            parameters.Add("?ReplyType", entity.ReplyType.ToString(), DbType.AnsiString, size: 30);
            parameters.Add("?TeamWorkAttachmentId", entity.TeamWorkAttachmentId, DbType.Int64, size: 20);
            parameters.Add("?ReplyContent", entity.ReplyContent?.Trim(), DbType.String);
            parameters.Add("?ReplyTime", DateTime.Now, DbType.DateTime);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<TeamWorkReplyEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<TeamWorkReplyEntity> Update(TeamWorkReplyEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("OA_TeamWorkReply", new string[] { "TeamWorkId", "ParticipantId", "ReplyType", "TeamWorkAttachmentId", "ReplyContent", "ReplyTime" }, new string[] { "TeamWorkReplyId" });
            sql = string.Format("{0} {1} WHERE A.TeamWorkReplyId=?TeamWorkReplyId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TeamWorkReplyId", entity.TeamWorkReplyId, DbType.Int64, size: 20);
            parameters.Add("?TeamWorkId", entity.TeamWorkId, DbType.Int64, size: 20);
            parameters.Add("?ParticipantId", entity.ParticipantId, DbType.Int64, size: 20);
            parameters.Add("?ReplyType", entity.ReplyType.ToString(), DbType.AnsiString, size: 30);
            parameters.Add("?TeamWorkAttachmentId", entity.TeamWorkAttachmentId, DbType.Int64, size: 20);
            parameters.Add("?ReplyContent", entity.ReplyContent?.Trim(), DbType.String);
            parameters.Add("?ReplyTime", entity.ReplyTime, DbType.DateTime);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<TeamWorkReplyEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> Delete(long teamWorkReplyId)
        {
            string sql = @"DELETE FROM OA_TeamWorkReply WHERE TeamWorkReplyId=?TeamWorkReplyId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TeamWorkReplyId", teamWorkReplyId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        public async Task<bool> DeleteBatch(long teamWorkId)
        {
            string sql = @"DELETE FROM OA_TeamWorkReply WHERE TeamWorkId=?TeamWorkId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TeamWorkId", teamWorkId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<TeamWorkReplyEntity> GetEntity(long teamWorkReplyId)
        {
            string sql = string.Format(@"{0} WHERE A.TeamWorkReplyId=?TeamWorkReplyId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TeamWorkReplyId", teamWorkReplyId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<TeamWorkReplyEntity>(sql, parameters);
        }

        public async Task<IEnumerable<TeamWorkReplyEntity>> GetList(long teamWorkId)
        {
            string sql = string.Format(@"{0} WHERE A.TeamWorkId=?TeamWorkId ORDER BY A.ReplyTime", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TeamWorkId", teamWorkId, DbType.Int64);
            return await this.databaseContext.Slave.QueryAsync<TeamWorkReplyEntity>(sql, parameters);
        }

        public async Task<(IEnumerable<TeamWorkReplyEntity>, int)> Query(long? teamWorkId, DateTime? start, DateTime? end, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (teamWorkId.HasValue)
            {
                wheres.Add("A.TeamWorkId=?TeamWorkId");
                parameters.Add("?TeamWorkId", teamWorkId, DbType.Int64);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("A.ReplyTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("A.ReplyTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("A.ReplyTime>=?Start AND A.ReplyTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY A.ReplyTime DESC LIMIT {2},{3}; 
                                        SELECT COUNT(1) 
                                        FROM OA_TeamWorkReply A
                                        LEFT JOIN OA_TeamWorkAttachment B ON A.TeamWorkAttachmentId=B.TeamWorkAttachmentId 
                                        LEFT JOIN OA_TeamWorkParticipant C ON A.ParticipantId=C.ParticipantId
                                        {1}",
                   QUERY,
                   wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                   (pageIndex - 1) * pageSize,
                   pageSize);
            return await this.databaseContext.Slave.QueryPageableListAsync<TeamWorkReplyEntity>(sql, parameters);
        }
    }
}
